<template>
  <div class="uni-upload-pro">
    <el-upload ref="upload" accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF,.doc,.docx,.txt,.xls,.xlsx,.rar,.zip" v-bind="uploadOriProps"
      :disabled="disabled" :action="action" :file-list="fileList" :on-success="handleSuccess" :on-remove="handleRemove"
      :before-remove='handleBeforeRemove' :on-preview="onPreviewEvent">
      <slot><i class="el-icon-plus"></i></slot>
    </el-upload>
  </div>
</template>
<script>

/**
 * 1、废弃 file-list 采用双向绑定
 * 2、默认 action 控件封装上传地址 `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${this.$cookies.get('token')}`
 * 3、disabled 属性不放在uploadOriProps中，方便做查看功能
 * 4、uploadOriProps 中支持el的原生属性和函数
 */
export default {
  name: 'uni-upload-pro',
  props: {
    /**
     * `Array`
     */
    value: {
      type: Array,
      default () {
        return []
      }
    },
    /**
     * el-upload 的原生属性支持
     */
    uploadOriProps: {
      type: Object,
      default () {
        return {}
      }
    },
    action: {
      type: String,
      default () {
        return `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${this.$cookies.get('token')}`
      }
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default () {
        return false
      }
    }
  },
  data () {
    return {
      fileList: [],
      refreshFileList: true
    }
  },
  watch: {
    // 父组件绑定进行刷新
    value: function (val) {
      if (this.refreshFileList) {
        this.fileList = val
      } else {
        this.refreshFileList = true
      }
    }
  },
  created () {
    // 初始化
    this.fileList = this.value
  },
  beforeMount () {
  },
  mounted () {
  },
  methods: {
    onPreviewEvent (file) {
      let onPreview = this.uploadOriProps['on-preview'] || this.uploadOriProps['onPreview']
      if (onPreview) {
        onPreview(file)
      } else {
        if (file) {
          let url = file.url ? file.url : file.response.data.url
          let name = file.name
          if (url) {
            let el = document.createElement('a')
            let event = new MouseEvent('click')
            el.href = this.$utils.getTokenUrl(url)
            el.download = name
            el.target = '_blank'
            el.dispatchEvent(event)
          }
        }
      }
    },
    // handleSuccess () {
    //   var arg = [].slice.call(arguments);
    //   arg.push(this.index);
    //   this.onSuccess.apply(this, arg)
    // },
    clearFiles () {
      this.$refs.upload.clearFiles()
    },
    // 重写默认的 success 事件
    handleSuccess (response, file, fileList) {
      // 设置状态
      file.status = 'fail'
      if (response && response.data && response.data.id) {
        file.status = 'success'
      } else {
        console.log('handleSuccess1', response, file, fileList)
        return this.$message.error(response.msg)
      }
      // 回写
      this.refreshFileList = false
      this.$emit('input', fileList ? fileList.map(c => c.response ? c.response.data : c) : [])
      if (this.uploadOriProps['on-success']) {
        this.uploadOriProps['on-success'](response, file, fileList)
      }
    },
    handleBeforeRemove (file, fileList) {
      let r = this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
      if (this.uploadOriProps['before-remove']) {
        return this.uploadOriProps['before-remove'](file, fileList)
      }
      return r
    },
    // 重写默认的remove事件
    handleRemove (file, fileList) {
      // 删除 物理文件
      this.deleteFile(file.response ? file.response.data.id : file.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.$message.error(res.msg)
          }
        })
      // 回写
      this.refreshFileList = false
      this.$emit('input', fileList ? fileList.map(c => c.response ? c.response.data : c) : [])
      // 函数钩子
      if (this.uploadOriProps['on-remove']) {
        this.uploadOriProps['on-remove'](file, fileList)
      }
    },
    // 文件删除
    deleteFile (id) {
      return this.$http.delete(`/oss/sysOss`, { 'data': [id] })
    }
    // // 上传之前
    // beforeUploadHandle (file) {
    //   this.num++
    // },
    // // 上传成功
    // successHandle (res, file, fileList) {
    //   if (res.code !== 0) {
    //     return this.$message.error(res.msg)
    //   }
    //   this.fileList = fileList
    //   this.num--
    //   if (this.num === 0) {
    //     this.$message({
    //       message: this.$t('prompt.success'),
    //       type: 'success',
    //       duration: 500,
    //       onClose: () => {
    //         this.visible = false
    //         this.$emit('refreshDataList')
    //       }
    //     })
    //   }
    // }
  }
}
</script>

<style>
.uni-upload-pro .el-upload-dragger {
  height: 100%;
  width: 100%;
}
.uni-upload-pro .el-upload--picture-card,
.uni-upload-pro .el-upload--picture {
  border: 0px;
}
.uni-upload-pro .el-upload--picture {
  width: 100%;
}
.uni-upload-pro .el-upload-dragger .el-icon-upload,
.uni-upload-pro .el-upload-dragger .el-icon-plus {
  margin: 0px 0 0px 0;
  height: 100%;
  width: 100%;
  border: 0px;
}
</style>
